using UnityEngine;
using System.Collections;

[RequireComponent(typeof(AudioSource))]

public class ThirdPersonCharacterAttack : MonoBehaviour
{
	public float punchSpeed = 1.0f;
	public float punchHitTime = 0.2f;
	public float punchTime = 0.4f;
	public Vector3 punchPosition = new Vector3(0f, 0f, 0.8f);
	public float punchRadius = 1.3f;
	public float punchHitPoints = 1.0f;
	
	public AudioClip punchSound;
	
	private bool busy = false;
	void Start()
	{
		animation["punch"].speed = punchSpeed;
	}
	
	void Update()
	{
		ThirdPersonController controller = GetComponent<ThirdPersonController>();
		if(!busy && Input.GetButtonDown("Fire1") && controller.IsGroundedWithTimeout() && !controller.IsMoving())
		{
			SendMessage("Did Punch");
			busy = true;
		}
	}
	
	public IEnumerator DidPunch()
	{
		animation.CrossFadeQueued("punch", 0.1f, QueueMode.PlayNow);
		yield return new WaitForSeconds(punchHitTime);
		
		Vector3 pos = transform.TransformPoint(punchPosition);
		//Check this declaration
		GameObject[] enemies = GameObject.FindGameObjectsWithTag("Enemy");
		
		foreach(GameObject go in enemies)
		{
			EnemyDamage enemy = go.GetComponent<EnemyDamage>();
			if(enemy == null)
			{
				continue;	
			}
			
			if(Vector3.Distance(enemy.transform.position, pos) < punchRadius)
			{
				enemy.SendMessage("ApplyDamage", punchHitPoints);
				
				if(punchSound)
				{
					audio.PlayOneShot(punchSound);	
				}
			}
		}
		yield return new WaitForSeconds(punchTime - punchHitTime);
		busy = false;
	}
	
	void OnDrawGizmosSelected()
	{
		Gizmos.color = Color.yellow;
		Gizmos.DrawWireSphere(transform.TransformPoint(punchPosition), punchRadius);
	}
}
